import { MyGameObject } from "./MyGameObject";
import { Wall } from "./Wall";
import { Snake } from './Snake';
import { Food } from "./food";
import { A_GIFS } from "./gif/all_gif";
import { BOMB } from './bomb';

export class GameMap extends MyGameObject { // 游戏地图加入了MYGame
                                    //一帧将会刷新一次，因为其他物品画过后会覆盖，所以地图也要画。                      
    constructor(ctx,parent,store){//构造函数
        super();

        this.ctx = ctx;// 这是canvas
        this.parent = parent;
        this.store = store;
        this.L = 0;

        this.rows = 30;
        this.cols = 31;

        this.inner_wall_counts = 50;
        this.walls = [];//画布上的墙。
        this.walls_pleace = [];//被覆盖的地区，包括food和墙
        this.real_time_map = [];//实时的地图，用来向后端传输。

        this.food = [];//画布上的食物

        this.step_count_a = 0;
        this.step_count_b = 0;//回放功能记录走过步数。


        if(store.state.user.id == store.state.pk.a_id && !store.state.record.is_record)
        this.Snake = [
            new Snake({id:store.state.pk.a_id,color:"#4876EC",r:this.rows - 2,c:1},this),
            new Snake({id:store.state.pk.b_id,color:"#F94848",r:1,c:this.cols - 2},this)
        ];
        else if(store.state.user.id == store.state.pk.b_id && !store.state.record.is_record)
        this.Snake = [
            new Snake({id:store.state.pk.b_id,color:"#4876EC",r:this.rows - 2,c:1},this),
            new Snake({id:store.state.pk.a_id,color:"#F94848",r:1,c:this.cols - 2},this)
        ];
        else
        this.Snake = [
            new Snake({id:store.state.pk.a_id,color:"#4876EC",r:this.rows - 2,c:1},this),
            new Snake({id:store.state.pk.b_id,color:"#F94848",r:1,c:this.cols - 2},this)
        ];

        this.gif = new A_GIFS();//处理一些GIF
    }

    // wall_is_also(g,sx,sy,tx,ty){//墙是否联通、
    //     if(sx == tx && sy ==ty) return true;

    //     g[sx][sy] = true;

    //     let dx = [-1, 0, 1,0],dy = [0,1,0,-1];
    //     for(let i  = 0 ;i<4 ; i++){
    //         let x = sx + dx[i],y = sy + dy[i];
    //         if(!g[x][y] && this.wall_is_also(g,x,y,tx,ty))
    //         return true;

    //     }
    //     return false;
    // }

    create_walls(){//造墙。
        // const g = [];

        // for(let r = 0; r< this.rows; r++){//初始化
        //     g[r] = [];
        //     for(let c = 0;c< this.cols;c++){
        //         g[r][c] = false;
        //     }
        // }

        // //给四周加上墙
        // for(let r = 0 ;r<this.rows; r++){
        //     g[r][0] = g[r][this.cols - 1] = true;
        // }
        // for(let c = 0;c< this.cols ;c++)
        // {
        //     g[0][c] = g[this.rows - 1][c] = true;
        // }

        // //创建随机障碍物

        // for(let i = 0 ; i< this.inner_wall_counts; i++)
        // {
        //     for(let j = 0; j< 1000;j++)
        //     {
        //         let r = parseInt(Math.random() * this.rows);
        //         let c = parseInt(Math.random() * this.cols);
        //         if(g[r][c] || g[this.rows - 1 -r ][this.cols -1 -c])continue;
        //         if(r == this.rows-2&&c == 1 || r == 1 && c == this.cols - 2)continue;//创建时有一些点不能创建
        //         g[r][c] = g[this.rows - 1 -r ][this.cols -1 -c] = true;
        //         break;
        //     }
        // }

        // const copy_g = JSON.parse(JSON.stringify(g));
        // if(this.wall_is_also(copy_g,this.rows - 2,1,1,this.cols-2)){

        const g = this.store.state.pk.game_map;
            for(let r = 0; r<this.rows;r++){   //画墙
                this.walls_pleace[r] = [];
                this.real_time_map[r] = [];
                for(let c = 0;c<this.cols;c++){
                    if(g[r][c]){
                        this.walls_pleace[r][c] = true;
                        this.real_time_map[r][c] = 1;
                        this.walls.push(new Wall(r,c,this));
    
                    }
                    else{
                        this.walls_pleace[r][c] = false;
                        this.real_time_map[r][c] = 0;
                    } 
                }
            }

            this.real_time_map[this.Snake[0].cells[0].r][this.Snake[0].cells[0].c] = 4;
            this.real_time_map[this.Snake[1].cells[0].r][this.Snake[1].cells[0].c] = 3;
        //     return true;
        // // }
        // else
        // {
        //     return false;
        // }
    }

    is_bomb(cell){//检测碰撞，杀掉蛇头
        for(let wall of this.walls)
        {//判断和墙的碰撞
            if(Math.abs(cell.x - wall.c - 0.5)<0.8&&Math.abs(cell.y - wall.r - 0.5)<0.8){
                new BOMB(cell.y-0.5,cell.x-0.5,this);
                return true;
            }
        }
        for(let snake of this.Snake)
        {
            for(let i = 0 ; i===0||i <= snake.cells.length - 2;i++)
            {
                if(cell.x === snake.cells[i].x && cell.y === snake.cells[i].y)continue;
                if(Math.sqrt(Math.pow((cell.x - snake.cells[i].x),2) + Math.pow((cell.y - snake.cells[i].y),2)) < 0.68) {
                    new BOMB(cell.y-0.5,cell.x-0.5,this);

                    return true;//判断和自己以及玩家2的碰撞

                }
            }
        }
        return false;
    }

    add_listening_events(){ //读取输入
            this.ctx.canvas.focus();
            const [snake0, snake1] = this.Snake;
            this.ctx.canvas.addEventListener("keydown", e =>{
                if(this.store.state.user.id == snake0.id)
                {
                        if(e.key === 'w')snake0.set_step(0);//this.snake0_w_down++;
                        else if(e.key === 's')snake0.set_step(1);//this.snake0_s_down++;
                        else if(e.key === 'a')snake0.set_step(2);//this.snake0_a_down++;
                        else if(e.key === 'd')snake0.set_step(3);//this.snake0_d_down++;
                }
                else if(this.store.state.user.id == snake1.id)
                {
                        if(e.key === 'w')snake1.set_step(0);//this.snake0_w_down++;
                        else if(e.key === 's')snake1.set_step(1);//this.snake0_s_down++;
                        else if(e.key === 'a')snake1.set_step(2);//this.snake0_a_down++;
                        else if(e.key === 'd')snake1.set_step(3);//this.snake0_d_down++;
                }
            })
        
        

        // 添加 keyup 事件监听器
        // this.ctx.canvas.addEventListener("keyup", e => {
        //     // 松开了有效键
        //     if(e.key === 'w')this.snake0_w_down = 0;
        //     else if(e.key === 's')this.snake0_s_down =0;
        //     else if(e.key === 'a')this.snake0_a_down=0;
        //     else if(e.key === 'd')this.snake0_d_down=0;
        //     else if(e.key === 'ArrowUp')this.snake1_w_down=0;
        //     else if(e.key === 'ArrowDown')this.snake1_s_down=0;
        //     else if(e.key === 'ArrowLeft')this.snake1_a_down=0;
        //     else if(e.key === 'ArrowRight')this.snake1_d_down=0;
        //     let snake0_down = this.snake0_a_down+this.snake0_d_down+this.snake0_s_down+this.snake0_w_down;
        //     let snake1_down = this.snake1_a_down+this.snake1_d_down+this.snake1_s_down+this.snake1_w_down;
        //         if(snake0_down === 0)snake0.set_step(4);
        //         if(snake1_down === 0)snake1.set_step(4);
        // });
    }

    game_over(id){//某一方失败
        if(id === this.Snake[0].id){
            // console.log(10)
            this.Snake[0].status = "die";
            this.store.commit("updateLoser","you");
        }
        else if(id === this.Snake[1].id){
            this.Snake[1].status = "die";
            this.store.commit("updateLoser","he");
        }
        
    }
    add_food(r,c){
        if(this.walls_pleace[r][c])return;

        this.food.push((new Food(r,c,this)));
        this.walls_pleace[r][c] = true;
        if(this.real_time_map[r][c] === 0)
        this.real_time_map[r][c] = 2;
    }

    start(){

        this.create_walls();
        // if(this.store.state.pk.botId === -1)
        if(this.store.state.record.is_record){
            let k =0;
                setInterval(() => {
                    if(this.Snake[0].status === "die" || this.Snake[1].status === "die" || this.store.state.record.food_x.length < k + 2){
                        return;
                    }
                    if(this.store.state.record.food_x[k] !== null && this.store.state.record.food_y[k] !== null &&this.store.state.record.food_x[k] !== undefined && this.store.state.record.food_y[k] !== undefined)
                        {
                            this.add_food(this.store.state.record.food_x[k],this.store.state.record.food_y[k]);
                            k++;
                        }
            }, 3000);


                setTimeout( ()=> {
                    
                }, 1000);
                    this.Snake[0].status = "move";
                    this.Snake[1].status = "move";  
        }
        else
        this.add_listening_events();

    }

    update_size() {
        this.L = parseInt(Math.min(this.parent.clientWidth / this.cols,this.parent.clientHeight / this.rows));//计算画布的单位长度（依据当前播放设备动态计算）
        this.ctx.canvas.width = this.L * this.cols;//画布长
        this.ctx.canvas.height = this.L * this.rows;// 画布宽
    }
    update(){
        this.update_size();
        this.render();
    }

    render(){
        const color_even = "#AAD751" , color_odd = "#A2D149";
        for(let r = 0 ; r< this.rows ; r++)
        {
            for(let c = 0 ; c< this.cols;c++)
            {
                if((r+c) % 2 == 0){
                    this.ctx.fillStyle = color_even;
                }else {
                    this.ctx.fillStyle = color_odd;
                }
                this.ctx.fillRect(c * this.L,r*this.L,this.L,this.L)

            }
        }

    }
}